package controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import model.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * Created by yvdedu.com on 2016/9/26.
 */
@WebServlet(urlPatterns = "/login_user")
public class login_user extends HttpServlet{

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String name=req.getParameter("name");
        String pwd=req.getParameter("pwd");
        if(name!=null&&pwd!=null){
            MySql mySql=new MySql();
            model.User user=mySql.getUserByName(name);
            if(user==null){
                resp.getWriter().print("用户名不存在，请重试！");
            }else{
                if(!user.getPwd().equals(pwd)){
                    resp.getWriter().print("对不起，密码错误，请重试");
                }else{
                    ObjectMapper mapper = new ObjectMapper();
                    String json = mapper.writeValueAsString(user);
                    req.getSession().setAttribute("user",mySql.getUserByName(name));
                    resp.getWriter().print(json);
                }
            }
        }else{
            resp.getWriter().print("用户名或密码不能为空！");
        }
    }
}
